
package com.zcp.wizard;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;

public class SystemClearActivity extends Activity implements View.OnClickListener {

    // 管理进程按钮
    private Button btnProcessManager;

    // 一键清理按钮
    private Button btnClear;

    private LinearLayout lineResult;

    // 小鸡动画图片，大背景
    private ImageView imageChickAnim;

    // 小鸡图片
    private ImageView imageChick;

    AnimationDrawable anim;

    public static final int RATE_TYPE_CPU = 0;

    public static final int RATE_TYPE_MEMORY = 1;

    public static final int RATE_TYPE_STORAGE = 2;

    public static final int RATE_TYPE_SDCARD = 3;

    public static final String F_SCALE_FREQ = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";

    public static final String F_CPU_INFO = "/proc/cpuinfo";

    // private static final String TAG = "SystemClearActivity";

    // handler Msg类型，停止动画
    private static final int MSG_TYPE_STOPANIM = 0;

    // handler Msg类型，一键清理进程
    private static final int MSG_TYPE_KILLPROCESS = 1;

    // handler Msg类型，恢复按钮和提示状态
    private static final int MSG_TYPE_RESUME = 2;

    private TextView tipText;

    private int score;

    SdcardStatusReceiver receiver;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.systemclear);

        imageChickAnim = (ImageView) findViewById(R.id.imageChickAnim);
        imageChick = (ImageView) findViewById(R.id.chick);
        lineResult = (LinearLayout) findViewById(R.id.lineResult);

        btnClear = (Button) findViewById(R.id.btnClear);
        btnClear.setOnClickListener(this);

        btnProcessManager = (Button) findViewById(R.id.btnProcessManager);
        btnProcessManager.setOnClickListener(this);
        anim = (AnimationDrawable) imageChickAnim.getBackground();
        TextView tv = (TextView) findViewById(R.id.score);
        tv.setTypeface(Typeface.createFromAsset(getAssets(), "font/WizardThin.ttf"));
        MyBroadcastReceiver.register(this);

        // 增加对sd卡状态的监听
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addDataScheme("file");
        receiver = new SdcardStatusReceiver();
        this.registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        try {
            MyBroadcastReceiver.unRegister(this);
            if (menuPopup != null && menuPopup.isShowing()) {
                menuPopup.dismiss();
            }
            menuPopup = null;
            lineResult = null;
            btnProcessManager = null;
            imageChickAnim = null;
            if (anim != null && anim.isRunning()) {
                anim.stop();
            }
            anim = null;
            btnClear = null;
            tipText = null;
            this.unregisterReceiver(receiver);
            if (handler != null) {
                handler.removeMessages(MSG_TYPE_KILLPROCESS);
                handler.removeMessages(MSG_TYPE_STOPANIM);
                handler.removeMessages(MSG_TYPE_RESUME);
            }
            handler = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
        initStatusData();
    }

    private void initStatusData() {

        // 获取sdcard信息
        String[] data = Util.getSdCardInfo(this);

        float sdcardUsage = Float.parseFloat(data[2]);
        setStatusBar(R.id.rate_sdcard_1, new int[] {
                R.id.rate_sdcard_2, R.id.rate_sdcard_3, R.id.rate_sdcard_4, R.id.rate_sdcard_5
        }, data[0], sdcardUsage, RATE_TYPE_SDCARD);

        TextView tv = (TextView) this.findViewById(R.id.total_sdcard);
        tv.setText(data[1]);

        // 获取手机内部存储信息
        data = Util.getStorageInfo(this);
        float storgeUsage = Float.parseFloat(data[2]);
        setStatusBar(R.id.rate_storage_1, new int[] {
                R.id.rate_storage_2, R.id.rate_storage_3, R.id.rate_storage_4, R.id.rate_storage_5
        }, data[0], storgeUsage, RATE_TYPE_STORAGE);
        tv = (TextView) this.findViewById(R.id.total_storage);
        tv.setText(data[1]);

        // 获取内存信息
        data = Util.getMemoryInfo(this);
        float memoryUsage = Float.parseFloat(data[2]);
        setStatusBar(R.id.rate_memory_1, new int[] {
                R.id.rate_memory_2, R.id.rate_memory_3, R.id.rate_memory_4, R.id.rate_memory_5
        }, data[0], memoryUsage, RATE_TYPE_MEMORY);
        tv = (TextView) this.findViewById(R.id.total_memory);
        tv.setText(data[1]);

        // 获取cpu信息
        data = Util.getCpuInfo();

        setStatusBar(R.id.rate_cpu_1, new int[] {
                R.id.rate_cpu_2, R.id.rate_cpu_3, R.id.rate_cpu_4, R.id.rate_cpu_5
        }, data[0], Float.parseFloat(data[2]), RATE_TYPE_CPU);
        tv = (TextView) this.findViewById(R.id.total_cpu);
        tv.setText(data[1]);

        // 设置分数及星级
        tv = (TextView) this.findViewById(R.id.score);

        score = Util.calculateScore(memoryUsage, storgeUsage, sdcardUsage);
        tv.setText(score + "");

        updateTipsAndChickStatus();
        RatingBar bar = (RatingBar) this.findViewById(R.id.scoreRate);
        float rate = (float)Math.ceil((double)score * 5 / 100f);
        bar.setRating(rate);
        btnProcessManager.setText(getString(R.string.manager_process, Util.getProcessNumber(this)));

    }

    /**
     * 更新提示语和小鸡的状态
     */
    private void updateTipsAndChickStatus() {
        tipText = (TextView) this.findViewById(R.id.tipText);
        tipText.setTextColor(getResources().getColor(R.color.text_other_color));// 测试用例77
        if (score < 60) {
            imageChick.setImageResource(R.drawable.chick_system_bad);
            tipText.setText(R.string.system_tips_bad);
            tipText.setTextColor(getResources().getColor(R.color.red));// 测试用例77
        } else if (score >= 60 && score < 80) {

            imageChick.setImageResource(R.drawable.chick_system_hot);
            tipText.setText(R.string.system_tips_low);
        } else {
            imageChick.setImageResource(R.drawable.chick);
            tipText.setText("");
        }
    }

    private void onClickNext() {
        Intent intent = new Intent(this, ProcessManagerActivity.class);
        this.startActivity(intent);
        this.getParent().overridePendingTransition(R.anim.zoomin, R.anim.zoomout); // 此为自定义的动画效果，下面两个为系统的动画效果

    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_TYPE_KILLPROCESS:
                    startAnim();
                    btnClear.setEnabled(false);
                    btnProcessManager.setText(R.string.manager_process_running);
                    btnProcessManager.setEnabled(false);
                    Context context = (Context) msg.obj;
                    onClickKillProcess(context);
                    WidgetUtils.updateSystemStats(context, false);
                    break;
                case MSG_TYPE_STOPANIM:
                    stopAnim();
                    int oldscore = score;
                    btnClear.setEnabled(true);
                    btnProcessManager.setText(getString(R.string.manager_process,
                            Util.getProcessNumber(SystemClearActivity.this)));
                    btnProcessManager.setEnabled(true);
                    initStatusData();
                    int newScore = score - oldscore;
                    if (newScore < 0)
                        newScore = 0;
                    tipText.setText(getString(R.string.system_tips_ok, newScore));
                    handler.sendEmptyMessageDelayed(MSG_TYPE_RESUME, 5000);
                    break;
                case MSG_TYPE_RESUME:
                    updateTipsAndChickStatus();

            }

        }

    };

    /**
     * 设置CPU、内存、手机存储、SD卡状态条
     * 
     * @param textViewId 用于显示内容的第一行文本框的ID
     * @param imageViewIds 剩下的四个ImageView的id，分别代表第二到第五行。
     * @param content 显示在第一行文本里的信息
     * @param usage 百分率，根据该值设置各行的显示状态。
     */
    private void setStatusBar(int textViewId, int[] imageViewIds, String content, float usage,
            int type) {

        int percent = (int) (usage * 10);

        TextView tv = (TextView) this.findViewById(textViewId);
        tv.setText(content);
        if (percent == 10) {
            setBackgroundResource(tv, type, false);
        } else if (percent == 9) {
            setBackgroundResource(tv, type, true);
        } else {
            tv.setBackgroundResource(R.drawable.rates_bar_0);
        }
        int len = imageViewIds.length;
        ImageView iv;
        for (int i = 0; i < len; i++) {

            iv = (ImageView) findViewById(imageViewIds[i]);
            switch (i) {
                case 0:
                    if (percent >= 8) {
                        setBackgroundResource(iv, type, false);
                    } else if (percent >= 7) {
                        setBackgroundResource(iv, type, true);
                    } else {
                        iv.setBackgroundResource(R.drawable.rates_bar_0);
                    }
                    break;
                case 1:
                    if (percent >= 6) {
                        setBackgroundResource(iv, type, false);
                    } else if (percent >= 5) {
                        setBackgroundResource(iv, type, true);
                    } else {
                        iv.setBackgroundResource(R.drawable.rates_bar_0);
                    }
                    break;
                case 2:
                    if (percent >= 4) {
                        setBackgroundResource(iv, type, false);
                    } else if (percent >= 3) {
                        setBackgroundResource(iv, type, true);
                    } else {
                        iv.setBackgroundResource(R.drawable.rates_bar_0);
                    }
                    break;
                case 3:
                    if (percent >= 2) {
                        setBackgroundResource(iv, type, false);
                    } else if (percent >= 1) {
                        setBackgroundResource(iv, type, true);
                    } else {
                        iv.setBackgroundResource(R.drawable.rates_bar_0);
                    }
                    break;
            }
        }

    }

    /**
     * 根据类型设置背景图片
     * 
     * @param view
     * @param type 数据类型
     * @param half 是否半格
     */
    private void setBackgroundResource(View view, int type, boolean half) {
        switch (type) {
            case RATE_TYPE_CPU:
                if (half) {
                    view.setBackgroundResource(R.drawable.rates_bar_1_half);
                } else {
                    view.setBackgroundResource(R.drawable.rates_bar_1);
                }
                break;
            case RATE_TYPE_MEMORY:
                if (half) {
                    view.setBackgroundResource(R.drawable.rates_bar_2_half);
                } else {
                    view.setBackgroundResource(R.drawable.rates_bar_2);
                }
                break;
            case RATE_TYPE_STORAGE:
                if (half) {
                    view.setBackgroundResource(R.drawable.rates_bar_3_half);
                } else {
                    view.setBackgroundResource(R.drawable.rates_bar_3);
                }
                break;
            case RATE_TYPE_SDCARD:
                if (half) {
                    view.setBackgroundResource(R.drawable.rates_bar_4_half);
                } else {
                    view.setBackgroundResource(R.drawable.rates_bar_4);
                }
                break;
        }
    }

    private PopupWindow menuPopup;

    private View menuLayout;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("menu");// 必须添加一个，其实用不到

        if (null == menuPopup) {

            menuLayout = getLayoutInflater().inflate(R.layout.options_menu, null);

            menuPopup = new PopupWindow(menuLayout, LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);

            menuPopup.setFocusable(true);// 必须，否则无法点击子view
            menuPopup.setOutsideTouchable(true);// 必须，否则点击其它区域无法关闭
            menuPopup.setBackgroundDrawable(new BitmapDrawable());// 同上
            menuPopup.setAnimationStyle(R.style.MenuAnimation);

            menuPopup.setTouchInterceptor(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getY() < 0) {
                        if (menuPopup.isShowing())
                            menuPopup.dismiss();
                    }
                    return false;
                }
            });

            menuLayout.setFocusableInTouchMode(true);// 必须，否则下面的事件不起作用

            menuLayout.setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // if (Constants.LOG_V)
                    // Log.v(TAG, "onKey(" + v + ", " + event + ")");
                    if ((keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_BACK)
                            && (menuPopup.isShowing())) {
                        menuPopup.dismiss();
                        return true;
                    }
                    return false;
                }
            });

            ((Button) menuLayout.findViewById(R.id.menu_help))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            Intent intent = new Intent(SystemClearActivity.this, HelpActivity.class);
                            startActivity(intent);
                            SystemClearActivity.this.getParent().overridePendingTransition(
                                    R.anim.zoomin, R.anim.zoomout);
                        }
                    });

            ((Button) menuLayout.findViewById(R.id.menu_about))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            Intent intent = new Intent(SystemClearActivity.this,
                                    AboutActivity.class);
                            startActivity(intent);
                            SystemClearActivity.this.getParent().overridePendingTransition(
                                    R.anim.zoomin, R.anim.zoomout);
                        }
                    });

            ((Button) menuLayout.findViewById(R.id.menu_exit))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            Util.exit(SystemClearActivity.this);
                        }
                    });

            ((Button) menuLayout.findViewById(R.id.menu_update))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            // Intent intent = new
                            // Intent(SystemClearActivity.this,
                            // UpdateActivity.class);
                            // startActivity(intent);
                            // SystemClearActivity.this.getParent().overridePendingTransition(
                            // R.anim.zoomin, R.anim.zoomout);
                            if (menuPopup.isShowing())
                                menuPopup.dismiss();
                            UpdateUtils.updateApp(SystemClearActivity.this);
                        }
                    });

        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menuPopup.isShowing())
            menuPopup.dismiss();
        else
            menuPopup.showAtLocation(findViewById(R.id.layoutRoot), Gravity.BOTTOM, 0, 0);
        return false;
    }

    @Override
    protected void onResume() {
        if (menuPopup != null && menuPopup.isShowing())
            menuPopup.dismiss();
        super.onResume();
    }

    protected void startAnim() {
        lineResult.setVisibility(View.GONE);
        imageChickAnim.setVisibility(View.VISIBLE);
        anim.start();
    }

    protected void stopAnim() {
        anim.stop();
        imageChickAnim.setVisibility(View.GONE);
        lineResult.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnClear:
                Message msg = new Message();
                msg.obj = this;
                msg.what = MSG_TYPE_KILLPROCESS;
                handler.sendMessage(msg);
                break;

            case R.id.btnProcessManager:
                onClickNext();
                break;
        }

    }

    /**
     * 响应杀死无用进程按钮事件。
     * 
     * @param context
     */
    private void onClickKillProcess(Context context) {
        Util.freeMemory(context);

        handler.sendEmptyMessageDelayed(MSG_TYPE_STOPANIM, 3000);
    }

    class SdcardStatusReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            initStatusData();
        }

    }

}
